import React, { useEffect } from 'react';
import { Select } from 'antd';

const { Option } = Select;

export default function CustomeSelect({
  async = false, // 异步获取option不做默认选中
  required,
  value,
  onChange,
  onHandleChange,
  items,
  initValue,
  disabled,
  placeholder = '请选择',
  search = false,
  mode,
}) {
  useEffect(() => {
    if (!async && required) {
      onChange(value || initValue);
    }
  }, []);
  const handleChange = (e, option) => {
    // 自定义表单控件change事件
    onChange(e, option);
    // 页面自定义change事件
    onHandleChange?.(e, option);
  };
  return (
    <Select
      allowClear={!required}
      value={value}
      showSearch={search}
      optionFilterProp="children"
      getPopupContainer={(triggerNode) => triggerNode.parentElement}
      disabled={disabled}
      onChange={(e, option) => handleChange(e, option)}
      placeholder={placeholder}
      mode={mode}
    >
      {items.map(({ value: key, name, ...optionInfos }) => (
        <Option key={key} value={key} optionInfo={optionInfos}>
          {name}
        </Option>
      ))}
    </Select>
  );
}
